﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CarHelpDesk.Web.Models.Repositories;
using CarHelpDesk.Web.Models;

namespace CarHelpDesk.Web.Controllers
{
    public class TagsController : Controller
    {
        ITagRepository repo { get; set; }
        
        public TagsController()
        {
            repo = new CarHelpDesk.Web.Models.Repositories.LinqRepositories.TagRepository();
        }

        public TagsController(ITagRepository cRepository)
        {
            repo = cRepository;
        }
        

        //
        // GET: /Tags/

        public ActionResult Index()
        {
            Tag t = new Tag();
            int p = t.QuestionTags.Count();
            
            return View(repo.GetTags());
        }

        [Authorize(Roles = "MegaModerator")]
        public ActionResult List()
        {
            Tag t = new Tag();
            int p = t.QuestionTags.Count();

            return View(repo.GetTags());
        }

        /// <summary>
        /// Get Tags For Question
        /// </summary>
        /// <param name="questionID"></param>
        /// <returns></returns>
        public ActionResult IndexQuestion(int questionID)
        {
            
            object o = GenerateHTMLString(repo.GetTagsByQuestion(questionID));

            return View();
        }


        public string GenerateHTMLString(IQueryable<Tag> tags)
        {
            string result = "<table id=\"tagsList\"> <tr>";
            int cnt = 1;
            string list = "";
            string temp = "<td> <a href=\"../../Questions/IndexTag/{0}\"><span id=\"tagSpan\">{0}</span></a> </td>";
            foreach (var item in tags) 
            {
                list += item.Title+" ";
                if (cnt % 8 == 0 )
                    result+= "</tr><tr>";
                result += string.Format(temp, item.Title);
            }
            result += "</tr></table>";
            ViewData["tableTags"] = result;
            ViewData["listTags"] = list;
            return result;
        }

        [HttpPost]
        public ActionResult EditQuestionTags(int questionID, FormCollection collection)
        {
            string value = "";
            if (collection.AllKeys.Contains("Tags"))
            {
                value = collection["Tags"].ToString();
                int[] TagsIDs;
                if (repo.HasAllTagName(
                    value.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries), out TagsIDs))
                {
                    repo.EditQuestionTags(TagsIDs, questionID, this.GetCurrentUserID());

                }
                else
                {
                    ModelState.AddModelError("", "Има грешно въведен етикет.");
                    return View();
                }
                
            }
            //GenerateHTMLString(repo.GetTagsByQuestion(questionID));
            return Json(new { Tags1 = GenerateHTMLString(repo.GetTagsByQuestion(questionID))});
        }
        
                
        //
        // GET: /Tags/Create
        [Authorize(Roles = "MegaModerator")]
        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Tags/Create
        [Authorize(Roles = "MegaModerator")]
        [HttpPost]
        public ActionResult Create(Tag tag)
        {
            try
            {
                int[] ids;
                if (!repo.HasAllTagName(new string[] { tag.Title }, out ids))
                {

                    tag.CreateDate = DateTime.Now;
                    tag.CreateBy = this.GetCurrentUserID();

                    repo.CreateTags(tag);
                }
                else
                {
                    ModelState.AddModelError("", "Вече има етикет с такова име.");
                    return View();

                }


                return RedirectToAction("List");
            }
            catch
            {
                return View();
            }
        }
        
        //
        // GET: /Tags/Edit/5
        [Authorize(Roles = "Moderator")] 
        public ActionResult Edit(int id)
        {
            Tag tag = repo.GetTagByID(id);
            if (tag == null) return RedirectToAction("Index");
            return View(tag);
        }

        //
        // POST: /Tags/Edit/5
        [Authorize(Roles = "Moderator")]
        [HttpPost]
        public ActionResult Edit(Tag tag)
        {
            try
            {
                // TODO: Add update logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Tags/Delete/5

        [Authorize(Roles = "MegaModerator")]
        public ActionResult Delete(int id)
        {
            Tag t = repo.GetTagByID(id);
            ViewData["DeleteText"] = string.Format("Сигурни ли сте, че изкате да изтриете етикет '{0}'?", t.Title);
            
            return View();
        }

        //
        // POST: /Tags/Delete/5
        [Authorize(Roles = "MegaModerator")]
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {

                Tag tag = repo.GetTagByID(id);
                if (tag.QuestionTags.Count() == 0)
                {
                    repo.Delete(tag);
                    return RedirectToAction("List");
                }
                else
                {
                    ViewData["DeleteText"] = "Етикет '" + tag.Title + "' не може да бъде изтрит. Има въпроси свързани с този етикет.";              
                    return View();
                } 
                
            }
            catch
            {
                return View();
            }
        }

        public ActionResult LookupTags(string q, int limit)
        {
            // We can get a list of tags from the database, but   
            // for this example, I will populate a list with values.  
            List<string> tags = repo.GetTags().Select(x => x.Title).ToList();
            // Select the tags that match the query, and get the   
            // number or tags specified by the limit.  

            //var retValue = tags;
            string[] tagsPart = tags.Where(x => x.ToLower().StartsWith(q.ToLower())).Take(limit).ToArray();
            // Return the result set as JSON        
            //return Json(tags);
            return Content(string.Join("\n", tagsPart));

        }
    }
}
